//
//  UIColor+Transform.m
//  ToolExample
//
//  Created by 唐可雄 on 2019/7/14.
//  Copyright © 2019 swustyc. All rights reserved.
//

#import "UIColor+Transform.h"

@implementation UIColor (Transform)

+ (UIColor *)colorTransformFrom:(UIColor *)fromColor to:(UIColor *)toColor progress:(CGFloat)progress {
    if (!fromColor || !toColor) {
        return nil;
    }
    
    progress = progress > 1 ? 1 : progress;
    progress = progress < 0 ? 0 : progress;
    
    
    CGFloat from_r = 0;
    CGFloat from_g = 0;
    CGFloat from_b = 0;
    size_t from_number = CGColorGetNumberOfComponents(fromColor.CGColor);
    if (from_number == 2) {
        CGFloat *fromComps = CGColorGetComponents(fromColor.CGColor);
        from_r = fromComps[0];
        from_g = fromComps[0];
        from_b = fromComps[0];
    } else if (from_number == 4) {
        CGFloat *fromComps = CGColorGetComponents(fromColor.CGColor);
        from_r = fromComps[0];
        from_g = fromComps[1];
        from_b = fromComps[2];
    } else {
        return nil;
    }
    
    CGFloat to_r = 0;
    CGFloat to_g = 0;
    CGFloat to_b = 0;
    size_t to_number = CGColorGetNumberOfComponents(toColor.CGColor);
    if (to_number == 2) {
        CGFloat *toComps = CGColorGetComponents(toColor.CGColor);
        to_r = toComps[0];
        to_g = toComps[0];
        to_b = toComps[0];
    } else if (to_number == 4) {
        CGFloat *toComps = CGColorGetComponents(toColor.CGColor);
        to_r = toComps[0];
        to_g = toComps[1];
        to_b = toComps[2];
    } else {
        return nil;
    }
    
    return [UIColor colorWithRed:(from_r*(1-progress) + to_r*progress)
                           green:(from_g*(1-progress) + to_g*progress)
                            blue:(from_b*(1-progress) + to_b*progress)
                           alpha:1];
}

@end
